<template>
  <!-- 登录 -->
  <header>
    <!-- 遮罩层 -->
    <div class="mask" @click="changeIsShowLogin(false)"></div>
    <!-- 登录框 -->
    <div class="loginbox">
      <!-- X按钮 -->
      <div class="close" @click="changeIsShowLogin(false)"></div>
      <section class="nav">
        <a
          href="#"
          :class="isShowContent ? 'active' : ''"
          @click="isShowContent = true"
          >手机号登录</a
        >
        |
        <a href="#" :class="isShowContent ? '' : 'active'" @click="weixinClick"
          >微信扫码登录</a
        >
      </section>
      <!-- 导航内容区域 -->
      <div class="content">
        <!-- 手机登录区域 -->
        <div class="phonelogin" v-show="isShowContent">
          <div class="row">
            <input
              type="text"
              name=""
              id=""
              placeholder="请输入手机号"
              v-model="phoneNumber"
              class="ipt"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              name=""
              id=""
              placeholder="请输入短信验证码"
              v-model="code"
              class="ipt"
            />
            <button class="btn btncode" @click="getcode" v-show="!isShowcount">
              获取验证码
            </button>
            <button class="btn btncode" v-show="isShowcount">
              {{ `${count}s` }}
            </button>
          </div>
          <div class="row">
            <button class="btn btnlogin" @click="submitFn">登录</button>
          </div>
        </div>
        <div id="weixin" class="qrcode" v-show="!isShowContent"></div>
      </div>
    </div>
  </header>
</template>

<script>
import { mapMutations, mapActions } from "vuex";
import { validatePhoneNumber } from "@/utils";
import {
  SendSMSAPI,
  PhoneLoginAPI,
  BindPhoneAPI,
  UserProfilesAPI,
} from "@/request/api";
export default {
  data() {
    return {
      isShowContent: true,
      msg: "向右滑动",
      phoneNumber: "",
      isShowcount: false,
      count: 5,
      code: "",
    };
  },
  methods: {
    ...mapMutations({
      changeIsShowLogin: "showModal/changeIsShowLogin",
      changeIsLogin: "Locol/changeIsLogin",
      changeIsisShowtoast: "showtoast/changeIsisShowtoast",
    }),
    ...mapActions({
      asyncIsshowToast: "showtoast/asyncIsshowToast",
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    codedown() {
      this.isShowcount = true;
      let timer = setInterval(() => {
        this.count--;
        if (this.count == 0) {
          clearInterval(timer);
          this.isShowcount = false;
          this.count = 6;
        }
      }, 1000);
    },
    toVerity() {
      if (!validatePhoneNumber(this.phoneNumber)) {
        // alert("请输入正确的手机号码");
        // this.changeIsisShowtoast({
        //   isShow:true,
        //   msg:'请输入正确的手机号码',
        //   type:'warning'
        // });
        // setTimeout(()=>{
        //   this.changeIsisShowtoast({
        //     isShow:false
        //   })
        // },1500)

        this.asyncIsshowToast({
          msg: "请输入正确的手机号码",
          type: "warning",
        });
        return false;
      }
      if (this.msg == "向右滑动" || this.msg == "再试一次") {
        // alert("请进行滑块验证");
        this.asyncIsshowToast({
          msg: "请进行滑块验证",
          type: "warning",
        });
        return false;
      }
      return true;
    },
    async getcode() {
      if (!this.toVerity()) return;
      let res = await SendSMSAPI({
        phone: this.phoneNumber.trim(),
      });
      // console.log(res);
      if (!res) return;
      if (res.data.code == 0) {
        // alert("短信验证码发送成功");
        this.asyncIsshowToast({
          msg: "短信验证码发送成功",
          type: "warning",
        });
        this.codedown();
      }
    },
    async submitFn() {
      if (!this.toVerity()) return;
      if (this.code.trim() === "") {
        // alert("请输入验证码");
        this.asyncIsshowToast({
          msg: "请输入验证码",
          type: "warning",
        });
        return;
      }
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        res = await BindPhoneAPI({
          verifyCode: this.code.trim(),
          phone: this.phoneNumber.trim(),
          uuid,
        });
      } else {
        res = await PhoneLoginAPI({
          verifyCode: this.code.trim(),
          phone: this.phoneNumber.trim(),
        });
      }
      if (!res) return;
      // console.log("登录成功", res);
      // alert("登录成功");
      this.asyncIsshowToast({
          msg: "登录成功",
          type: "warning",
        });
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      this.changeIsShowLogin(false);
      this.changeIsLogin(true);
      // console.log("登录成功");
      localStorage.removeItem("uuid");
      this.$router.push(this.$route.path);

      let uRes = await UserProfilesAPI();
      // console.log("用户信息", uRes);
    },
    weixinClick() {
      // 点击切换微信扫码登录这一项，并向微信扫码登录
      this.isShowContent = false;
      // 微信登录第一步：申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLC5pbXBvd2VyQm94IC5pbmZvewogICAgZGlzcGxheTogbm9uZTsKfSAgICAKLmltcG93ZXJCb3ggcXJjb2RlewogICAgbWFyZ2luLXRvcDogMjBweDsKfQ==",
      });
    },
  },
};
</script>
 
<style lang = "less" scoped>
header {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  .mask {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
  }
  .loginbox {
    position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
    top: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    .close {
      position: absolute;
      width: 22px;
      height: 22px;
      right: 55px;
      top: 10px;
      background: url("../assets/img/close.png");
    }
    .nav {
      display: flex;
      justify-content: center;
      padding-top: 55px;
      font-size: 22px;
      a {
        text-decoration: none;
        padding: 0 15px;
        color: #9b9ab3;
        &.active {
          color: #030303;
        }
      }
    }
    .content {
      width: 355px;
      margin: 20px auto 0;
      height: 200px;
      .phonelogin {
        .row {
          display: flex;
          margin-bottom: 25px;
        }
        .ipt {
          border: 1px solid #ccc;
          border-radius: 5px;
          flex: 1;
          height: 50px;
          padding-left: 12px;
          outline: none;
        }
        .btn {
          border: none;
          cursor: pointer;
          line-height: 50px;
        }
        .btnlogin {
          color: #fff;
          width: 100%;
          background-color: #0a328e;
        }
        .btncode {
          margin-left: 10px;
          width: 87px;
          border-radius: 5px;
        }
      }
    }
  }
}
#weixin {
  /* background-color: #fcf; */
  display: flex;
  justify-content: center;
  margin-top: -20px;
}
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>